package com.cloud.class05.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class RateLimitController {
    @GetMapping("/rateLimit/byUrl")
    public String byUrl() {
        return "按rest地址限流测试OK";
    }

    @GetMapping("/rateLimit/byResource")
    // @SentinelResource 注解作用：对资源进行限流  value ：向Sentinel中展示资源名称   blockHandler：限流后执行的方法
    @SentinelResource(value = "byResourceSentinelResource", blockHandler = "handleException")
    public String byResource() {
        return "按资源名称SentinelResource限流测试ok";
    }

    public String handleException(BlockException e) {
        return "服务不可用@SentinelResource启动异常，o(╥﹏╥)o";
    }

    // @SentinelResource 注解作用：对资源进行限流  value ：向Sentinel中展示资源名称   blockHandler：限流后执行的方法
    // fallback：降级后执行的方法
    @GetMapping("/rateLimit/doAction/{p1}")
    @SentinelResource(value = "doActionSentinelResource", blockHandler = "doActionBlockHandler"
            , fallback = "doActionFallback")
    public String doAction(@PathVariable("p1") Integer p1) {
        if (p1 == 0) {
            // RuntimeException及其它子类都属于运行时异常，其他异常属于编译时异常
            throw new RuntimeException("参数异常,p1不能等于0");
        }
        return "doActionSentinelResource都不会限流降级";

    }

    // 自定义限流与降级方法时，请求地址中有路劲参数时，需要在自定义限流与降级方法中，添加对应的参数
    public String doActionBlockHandler(@PathVariable("p1") Integer p1,BlockException e) {
        log.error("sentinel配置自定义限流了:{}", e);
        return "sentinel配置自定义限流了";

    }

    public String doActionFallback(@PathVariable("p1") Integer p1, Throwable e) {
        log.error("程序逻辑异常了:{}", e);
        return "程序逻辑异常了"+"\t"+e.getMessage();
    }


    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey",blockHandler = "dealHandler_testHotKey")
    public String testHotKey(@RequestParam(value = "p1",required = false) String p1,

                             @RequestParam(value = "p2",required = false) String p2){
        return "------testHotKey";
    }
    public String dealHandler_testHotKey(String p1,String p2,BlockException exception)
    {
        return "-----dealHandler_testHotKey";
    }





}
